package andriod.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

public class StringProcessor implements JsonValueProcessor {
	private String[] block = new String[]{
			"<\\s*/\\s*div\\s*>",//div
			"<\\s*br\\s*/+\\s*>",//br
			"<\\s*/\\s*tr\\s*",//tr
			"<\\s*/\\s*table\\s*>"};//table
	String RegEx_spe = "\\&[^;]+;";
	String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
	String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";

	@Override
	public Object processArrayValue(Object arg0, JsonConfig arg1) {
		if(arg0 instanceof String){
			Pattern pattern = Pattern.compile("<[^>]+>");
			String str = (String) arg0;
			Matcher matcher = pattern.matcher(str);
			boolean flag;
			while(matcher.find()){
				String matchedStr = matcher.group();
				flag = true;
				for (String b:block) {
					if(matchedStr.matches(b)){
						str = str.replaceFirst(b, "\n");
						flag=false;
						break;
					}
				}
				if(flag){
					str = str.replaceFirst("<[^>]+>", "");
				}
			}
			str = str.replaceAll(regEx_style, "");
			str = str.replaceAll(regEx_script, "");
			return str.replaceAll(RegEx_spe, "");
		}
		return arg1;
	}

	@Override
	public Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {
		if(arg1 instanceof String){
			Pattern pattern = Pattern.compile("<.*?>");
			String str = (String) arg1;
			Matcher matcher = pattern.matcher(str);
			boolean flag;
			while(matcher.find()){
				String matchedStr = matcher.group();
				flag = true;
				for (String b:block) {
					if(matchedStr.matches(b)){
						str = str.replaceFirst(b, "\n");
						flag=false;
						break;
					}
				}
				if(flag){
					str = str.replaceFirst("<.*?>", "");
				}
			}
			return str;
		}
		return arg1;
	}
}
